<?php
/**
 *翻译转劳保局送件
*/
namespace app\admin\controller;
use app\admin\controller\Admin;
use PhpOffice\PhpWord\TemplateProcessor;
use think\facade\App;
use think\facade\Db;
use think\log\ChannelSet;
use xhadmin\service\admin\record\CustomerService;
use xhadmin\db\Customer as CustomerDb;
use think\facade\Cache;
use think\facade\Log;

class Stepthree extends Admin {


	/*会员管理*/
	function index(){
        if (!$this->request->isAjax()){
			return $this->display('index');
		}else{
            $limit  = $this->request->post('limit', 0, 'intval');
			$offset = $this->request->post('offset', 0, 'intval');
			$page   = floor($offset / $limit) +1 ;

			$id_card= $this->request->param('id_card', '', 'strip_tags,trim');
			$first_name = $this->request->param('first_name', '', 'strip_tags,trim');
			$birth_year = $this->request->param('birth_year', '', 'strip_tags,trim');
			$last_name = $this->request->param('last_name', '', 'strip_tags,trim');
            $id= $this->request->param('id', '', 'strip_tags,trim');

            if(!empty($id)){
                $where['id'] = ['=',$id];
            }
            if(!empty($id_card)){
                $where['id_card'] = ['like','%'.$id_card.'%'];
            }
            if(!empty($birth_year)){
                $where['birth_day'] = ['like','%'.$birth_year.'%'];
            }
            if(!empty($first_name)){
                $where['first_name|last_name|passport_info'] = ['like','%'.$first_name.'%'];
            }
            /*if(!empty($last_name)){
                $where['last_name'] = ['like','%'.$last_name.'%'];
            }*/
            $where['status'] = ['=',3];
			$limit = ($page-1) * $limit.','.$limit;
            //p($where);exit;
			try{
				$res = CustomerService::pageList(formatWhere($where),$limit,'*',$orderby = 'id desc');
				foreach ($res['list'] as $key=>&$val) {
				    $val['work_year_month'] = $val['work_year'].'年'.$val['work_month'].'个月';
                    $val['name'] = $val['first_name'].' '.$val['last_name'];
                }
				$list = $res['list'];
			}catch(\Exception $e){
				exit($e->getMessage());
			}

			$data['rows']  = $list;
			$data['total'] = $res['count'];
			return json($data);
		}
	}


    /*批量设定翻译*/
    function zhipai() {
        if (!$this->request->isPost()){
            $ids = $this->request->param('id');
            $this->view->assign('id',$ids);
            return $this->display('stepthree/zhipai');
        }else{
            $postField = 'id,translater_id';
            $data = $this->request->only(explode(',',$postField),'post');
            //p($data);exit;
            //$info = CustomerDb::getInfo($data['id']);
            $where['id'] = $ids = explode(',',$data['id']);
            try {
                $now = time();
                Db::startTrans();
                unset($data['id']);
                CustomerService::editWhere($where,$data);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            return json(['status'=>'00','msg'=>'修改成功']);
        }
    }

    /*改为转为台湾代表处送件状态*/
    function status() {
        if (!$this->request->isPost()){
            /*$id = $this->request->get('id','','intval');
            if(!$id) $this->error('参数错误');
            $info = CustomerDb::getInfo($id);
            $id_card_lsg_fee = Db::name("customer")->field('id_card_lsg_fee')
                ->where([['status','>=',4],['id_card_lsg_fee','>=',0]])->order('update_time','desc')->find();
            $pass_port_lsg_fee = Db::name("customer")->field('pass_port_lsg_fee')
                ->where([['status','>=',4],['pass_port_lsg_fee','>=',0]])->order('update_time','desc')->find();

            //$id_card_fee =
            $this->view->assign('id_card_lsg_fee',
                empty($id_card_lsg_fee)?1530:$id_card_lsg_fee['id_card_lsg_fee']);
            $this->view->assign('pass_port_lsg_fee',
                empty($pass_port_lsg_fee)?1020:$pass_port_lsg_fee['pass_port_lsg_fee']);
            $this->view->assign('info',checkData($info));*/
            $ids = $this->request->param('id');
            $this->view->assign('ids',$ids);
            $this->view->assign('id_card_lsg_fee', 1530);
            $this->view->assign('pass_port_lsg_fee', 0);
            return $this->display('stepthree/status');
        }else{
            $postField = 'id,status,id_card_lsg_fee,pass_port_lsg_fee,ggz';
            $data = $this->request->only(explode(',',$postField),'post');
            //$info = CustomerDb::getInfo($data['id']);
            $where['id'] = $ids = explode(',',$data['id']);
            //$data['id_card_lsg_fee'] = $data['ggz']*510;
            //p($data);exit;
            try {
                $now = time();
                Db::startTrans();
                unset($data['id']);
                CustomerService::editWhere($where,$data);
                $turnover = $profit_loss_log =[];
                //损益表
                foreach ($ids as $id) {
                    $data['id'] = $id;
                    $info = CustomerDb::getInfo($data['id']);
                    $profit_id_card_lsg_fee = [
                        'subject' => 50,
                        'income_amount' =>0,
                        'outcome_amount' =>$data['id_card_lsg_fee'],
                        'related_index' =>$data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($profit_loss_log,$profit_id_card_lsg_fee);
                    $profit_pass_port_lsg_fee = [
                        'subject' => 60,
                        'income_amount' =>0,
                        'outcome_amount' =>$data['pass_port_lsg_fee'],
                        'related_index' =>$data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($profit_loss_log,$profit_pass_port_lsg_fee);
                    $turnover_id_card_lsg_fee = [
                        'type' =>1,
                        'sub_type' =>4,
                        'subject' =>50,
                        'director_id' =>$info['director_id'],
                        'introducer_id' =>$info['is_introducer'] ==1?$info['introducer_id']:0,
                        'customer_id' => $data['id'],
                        'customer_idcard' =>$info['id_card'],
                        'amount' => $data['id_card_lsg_fee'],
                        'related_index' => $data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($turnover,$turnover_id_card_lsg_fee);
                    $turnover_pass_port_lsg_fee = [
                        'type' =>1,
                        'sub_type' =>4,
                        'subject' =>60,
                        'director_id' =>$info['director_id'],
                        'introducer_id' =>$info['is_introducer'] ==1?$info['introducer_id']:0,
                        'customer_id' => $data['id'],
                        'customer_idcard' =>$info['id_card'],
                        'amount' => $data['pass_port_lsg_fee'],
                        'related_index' => $data['id'],
                        'created_time' => $now,
                        'created_d' => date('Ymd',$now),
                        'created_y' => date('Y',$now),
                        'created_ym' => date('Ym',$now),
                    ];
                    array_push($turnover,$turnover_pass_port_lsg_fee);
                    $customer_log[] = [
                        'c_id' => $data['id'],
                        'id_card' => $info['id_card'],
                        'status' => $data['status'],
                        'create_by' => session('admin.userid'),
                        'create_time' => $now,
                    ];
                }

                Db::name("customer_log")->insertAll($customer_log);
                //流水表
                Db::name("turnover")->insertAll($turnover);
                Db::name("profit_loss_log")->insertAll($profit_loss_log);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            return json(['status'=>'00','msg'=>'修改成功']);
        }
    }


	/*修改*/
	function update(){
		if (!$this->request->isPost()){
			$id = $this->request->get('id','','intval');
			if(!$id) $this->error('参数错误');
            $info = CustomerDb::getInfo($id);
            //查找翻译信息
            if(isset($info['translater_id']) && !empty($info['translater_id'])) {
                $translator = Db::name("translator")->field('*')->where(['id'=>$info['translater_id']])->find();
            }

            //$info['idcard_info']['']
            if(empty($info['idcard_info'])) {
                $idcard_info = [
                    'id_card' => $info['id_card'],
                    'expiry_day' => !empty($info['expiry_date']) ? date('Y-m-d', strtotime($info['expiry_date'])) : '',
                    'addr'=>$info['addr'],
                    'number' => '',
                    'number_1' => '',
                    'number_2' => '',
                    'number_3' => !empty($info['id_card_upside_two']) ? $info['id_card_upside_two'] : '',
                    'religion' => !empty($info['religion']) ? $info['religion'] : '佛教',
                    'birth_day' => !empty($info['birth_day']) ? date('Y-m-d', strtotime($info['birth_day'])) : '',
                    'first_name' => !empty($info['first_name']) ? $info['first_name'] : '',
                    'last_name' => !empty($info['last_name']) ? $info['last_name'] : '',
                    'sign_name' => '',
                    'number_day' => '',
                    'numer_user' => isset($translator['name'])?$translator['name']:'吴明',
                    'dispatch_day' => '',//签证日期
                    'numer_sign_day' => date('Y-m-d'),
                    'id_card_posive_no' => '',
                    'id_card_upside_no' => !empty($info['id_card_upside_no']) ? $info['id_card_upside_no'] : '',
                ];
                $info['idcard_info'] = json_encode($idcard_info);
            }


            if(empty($info['passport_info'])) {
                $passport_info = [
                    'user_2_day' =>  date('Y-m-d'),
                    'user_2_name' => '',
                    'user_2_date1' => date('Y-m-d'),
                    'lastData_time' => date('Y-m-d'),
                    'proveData_time' =>'',
                    'user_2_signNum1' =>'',
                    'user_2_signNum2' =>'',
                    'user_2_person1' =>'CHATURONT CHAIYAKAM',
                    'user_2_person2' =>'MISS PRANEE PHOMSUPAR',
                    'user_2_person3' =>'Mr.Chaturont Chaiyakam',
                    'personApplytion' => $translator['name']?$translator['name']:'吴   惠',
                ];
                $passport_info['arr'][0] = [
                    'user_2_en' => $info['first_name'].$info['last_name'],
                    'user_2_th' => $info['first_name'].$info['last_name'],
                    'user_2_sex' => '-',
                    'user_2_kind' => '-',
                    'user_2_statu' => '-',
                    'user_2_number' => '-',
                    'user_2_codeNum' => $info['id_card'],
                    'user_2_endDate' => date('Y-m-d'),
                    'user_2_birthDay' => date('Y-m-d'),
                    'user_approveDay' => date('Y-m-d'),
                    'user_2_microfilm' => '-'
                ];
                $info['passport_info'] = json_encode($passport_info);
            }
            //p($info['idcard_info']);exit;
            //p($info);exit;
			$this->view->assign('info',checkData($info));
            return $this->display('stepthree/info');
		}else{
		    $type = $this->request->request('type');
            $id = $this->request->request('id');

            $content = file_get_contents('php://input');
            $post    = (array)json_decode($content, true);
		    //$a = json_decode($this->request->post(),true);
            //p($post);exit;
            $data['id'] = $id;
            if($type == 1) {
                $data['idcard_info'] = $content;
            } else if($type == 2) {
                $data['passport_info'] = $content;
            } else {
                $data = $post;
                $data['id'] = $id;
            }
            //p($data);exit;
			try {
                CustomerService::update($data);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'修改成功']);
		}
	}


    /*修改*/
    function updateFee(){
        $postField = 'id,id_card_lsg_fee,pass_port_lsg_fee';
        $data = $this->request->only(explode(',',$postField),'post');
        try {
            CustomerService::update($data);
            if(!empty($data['pass_port_lsg_fee'])) {
                Db::name("turnover")->where(['related_index'=>$data['id'],'subject'=>60])->update(['amount'=>$data['pass_port_lsg_fee']]);
                Db::name("profit_loss_log")->where(['related_index'=>$data['id'],'subject'=>60])->update(['outcome_amount'=>$data['pass_port_lsg_fee']]);
            }
            if(!empty($data['id_card_lsg_fee'])) {
                Db::name("turnover")->where(['related_index'=>$data['id'],'subject'=>50])->update(['amount'=>$data['id_card_lsg_fee']]);
                Db::name("profit_loss_log")->where(['related_index'=>$data['id'],'subject'=>50])->update(['outcome_amount'=>$data['id_card_lsg_fee']]);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return json(['status'=>'00','msg'=>'修改成功']);

    }

	/*删除*/
	function delete(){
		$idx =  $this->request->post('ids', '', 'strip_tags');
		if(!$idx) $this->error('参数错误');
		try{
			$where['id'] = explode(',',$idx);
            CustomerService::delete($where);
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
		return json(['status'=>'00','msg'=>'操作成功']);
	}

	/*查看数据*/
	function view(){
		$id = $this->request->get('id','','intval');
		if(!$id) $this->error('参数错误');
		try{
			$this->view->assign('info',checkData(CustomerDb::getInfo($id)));
			return $this->display('record/customer/view');
		} catch (\Exception $e){
			$this->error($e->getMessage());
		}
	}



    function getThumbPic(){
        $detail = $this->request->post('detail','','strval');
        preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/',$detail,$allImg);
        return json(['status'=>'00','imgurl'=>$allImg[1][0]]);
    }

    //Array
    //(
    //    [addr] => Maha Sarakham 省Kantharawichai 縣Khwao  鎮17村56號
    //    [addr_1] => Maha Sarakham
    //    [addr_2] => Kantharawichai
    //    [addr_3] => Khwao
    //    [addr_4] => 17村56號
    //    [number] => 067521
    //    [id_card] => 3440600645089
    //    [number_1] => BKK100
    //    [number_2] => E3439032
    //    [number_3] => ME0–1111974-26
    //    [religion] => 佛教
    //    [birth_day] => 30/03/2020
    //    [last_name] => bryant
    //    [sign_name] => 签名
    //    [expiry_day] => 2020年03月30日
    //    [first_name] => kobe
    //    [number_day] => 2019-03-30
    //    [numer_user] => 小明
    //    [dispatch_day] => 2020年03月30日
    //    [numer_sign_day] => 2020年03月30日
    //    [id_card_posive_no] => 4404-02-03011032
    //    [id_card_upside_no] => BORA-9.2-02-2560
    //)
    //Array
    //(
    //    [arr] => Array
    //    (
    //        [0] => Array
    //            (
    //            [user_2_en] => WICHAI BAONAK
    //            [user_2_th] => WICHAI BAONAK
    //            [user_2_sex] => 男性
    //            [user_2_kind] => 5-普通
    //            [user_2_statu] => c-取消
    //            [user_2_number] => L109136
    //            [user_2_codeNum] => 3-4404-00405-49-1
    //            [user_2_endDate] => 2020-03-30
    //            [user_2_birthDay] => 1957-03-30
    //            [user_approveDay] => 1991-03-30
    //            [user_2_microfilm] => M934 0197 00
    //            )
    //    )
    //    [user_2_day] => 2020-03-30
    //    [user_2_name] => WANIDAR
    //    [user_2_date1] => 2019-11-27
    //    [lastData_time] => 2020-03-30
    //    [proveData_time] => 2019-02-28
    //    [user_2_person1] => CHATURONT CHAIYAKAM
    //    [user_2_person2] => MISS PRANEE PHOMSUPAR
    //    [user_2_person3] => Mr.Chaturont Chaiyakam
    //    [personApplytion] => 吴   惠
    //    [user_2_signNum1] => 067520
    //    [user_2_signNum2] => BKK100
    //)
    //导出身份证护照
    function exportWord($cid='') {

        if(empty($cid)){
            $id = $this->request->request('id','','intval');
        }else{
            $id=$cid;
        }
        //$param = !empty($arr) ? $arr : $this->request->param();
        $info = Db::name("customer")->field('*')->where(['id'=>$id])->find();
        //p($info);
//        if(empty($info['idcard_info']) || empty($info['passport_info'])) {
//            if(!empty($cid)){
//               return ['code'=>'500','msg'=>'信息缺少,请补全信息'];
//            }
//            return json(['code'=>'500','msg'=>'信息缺少,请补全信息']);
//        }
        $idcard_info = $passport_info = [];
        $data=[];
        //查找翻译信息
        if(isset($info['translater_id']) && !empty($info['translater_id'])) {
            $translator = Db::name("translator")->field('*')->where(['id'=>$info['translater_id']])->find();
        }
        //p($translator);exit;
        try {
            list($idcard_info,$passport_info) = [json_decode($info['idcard_info'],1),json_decode($info['passport_info'],1)];
            if(empty($idcard_info)) {
                if(empty($info['idcard_info'])) {
                    $idcard_info = [
                        'id_card' => $info['id_card'],
                        'expiry_day' => !empty($info['expiry_date']) ? date('Y-m-d', strtotime($info['expiry_date'])) : '',
                        //'addr'=>'Maha Sarakham Kantharawichai Khwao 17村56號',
                        'addr' => !empty($info['addr']) ? $info['addr'] : '',
                        'number' => '',
                        'number_1' => '',
                        'number_2' => '',
                        'number_3' => !empty($info['id_card_upside_two']) ? $info['id_card_upside_two'] : '',
                        'religion' => !empty($info['religion']) ? $info['religion'] : '佛教',
                        'birth_day' => !empty($info['birth_day']) ? date('Y-m-d', strtotime($info['birth_day'])) : '',
                        'first_name' => !empty($info['first_name']) ? $info['first_name'] : '',
                        'last_name' => !empty($info['last_name']) ? $info['last_name'] : '',
                        'sign_name' => '',
                        'number_day' => '',
                        'numer_user' => $translator['name']?$translator['name']:'吴明',
                        'dispatch_day' => '',//签证日期
                        'numer_sign_day' => date('Y-m-d'),
                        'id_card_posive_no' => '',
                        'id_card_upside_no' => !empty($info['id_card_upside_no']) ? $info['id_card_upside_no'] : '',
                    ];
                    //$info['idcard_info'] = json_encode($idcard_info);
                }
            }
            if(empty($passport_info)) {
                $passport_info = [
                    'user_2_day' =>  date('Y-m-d'),
                    'user_2_name' => 'WANIDAR',
                    'user_2_date1' => date('Y-m-d'),
                    'lastData_time' => date('Y-m-d'),
                    'proveData_time' =>date('Y-m-d'),
                    'user_2_signNum1' =>'',
                    'user_2_signNum2' =>'',
                    'user_2_person1' =>'CHATURONT CHAIYAKAM',
                    'user_2_person2' =>'MISS PRANEE PHOMSUPAR',
                    'user_2_person3' =>'Mr.Chaturont Chaiyakam',
                    'personApplytion' => $translator['name']?$translator['name']:'吴明',
                ];
                $passport_info['arr'][0] = [

                    'user_2_en' => $info['first_name'].' '.$info['last_name'],
                    'user_2_th' => $info['first_name'].' '.$info['last_name'],
                    'user_2_sex' => '-性',
                    'user_2_kind' => '-普通',
                    'user_2_statu' => '-取消',
                    'user_2_number' => '-',
                    'user_2_codeNum' => $info['id_card'],
                    'user_2_endDate' => '-',
                    'user_2_birthDay' => !empty($info['birth_day']) ? date('Y-m-d', strtotime($info['birth_day'])) : '',
                    'user_approveDay' => '-',
                    'user_2_microfilm' => '-'
                ];
            }


            $dir = App::getBasePath().'../public/template/idcard_new.docx';
            $document = new TemplateProcessor($dir);
            //写入信息
            //$document->setValue('test', $data['test']);
            foreach ($idcard_info as $key=>&$value) {
                /*if(in_array($key,['dispatch_day','expiry_day','numer_sign_day'])) {
                    $idcard_info[$key] = date('Y年m月d日');
                }
                if($key=='birth_day') {
                    $idcard_info[$key] = date('d/m/Y');
                }
                if($key=='addr') {
                    $addrArr = explode(',',$value);
                    $idcard_info[$key] = $addrArr[0].' 省'.$addrArr[1].' 縣'.$addrArr[2].' 鎮'.$addrArr[3];
                }*/
                $document->setValue($key, $value);
            }
            $passport_info_bak = [];
            $i = 0;
            $passport_info_bak[0] = $passport_info['user_2_day'];
            $passport_info_bak[1] = $passport_info['user_2_name'];
            $passport_info_bak[2] = $passport_info['user_2_date1'];
            $passport_info_bak[3] = $passport_info['lastData_time'];
            $passport_info_bak[4] = $passport_info['proveData_time'];
            $passport_info_bak[5] = $passport_info['user_2_person1'];
            /*$passport_info_bak[6] = $passport_info['user_2_person2'];
            $passport_info_bak[7] = $passport_info['user_2_person3'];*/
            $passport_info_bak[6] = $passport_info['idRzInfo1']['name'];
            $passport_info_bak[7] = $passport_info['idSjInfo']['name'];
            $passport_info_bak[8] = $passport_info['personApplytion'];
            $passport_info_bak[9] = $passport_info['user_2_signNum1'];
            $passport_info_bak[10] = $passport_info['user_2_signNum2'];
            foreach ($passport_info_bak as $key=>$value) {
                $document->setValue($key, $value);
            }
            //p($info);
            //p($idcard_info);
            //p($passport_info);exit;
            if($passport_info['arr']) {
                $arr = $passport_info['arr'];
                $row1 = count($passport_info['arr']);
                $document->cloneRow('no',$row1);//复制行
                for($i=0;$i<$row1;$i++) {
                    $document->setValue("no#" . ($i + 1), $i+1);
                    $document->setValue("aa#" . ($i + 1), $arr[$i]['user_2_number'].'<w:br />'.$arr[$i]['user_2_th'].'<w:br />'.$arr[$i]['user_2_en']);
                    $document->setValue("ab#" . ($i + 1), $arr[$i]['user_2_codeNum']);
                    $document->setValue("ac#" . ($i + 1), date('d/m/Y',strtotime($arr[$i]['user_2_birthDay'])).'<w:br />'.$arr[$i]['user_2_sex'].'<w:br />'.$arr[$i]['user_2_microfilm']);
                    $document->setValue("ad#" . ($i + 1), date('d/m/Y',strtotime($arr[$i]['user_approveDay'])).'<w:br />'.$arr[$i]['user_2_kind'].'<w:br />'.$arr[$i]['user_2_statu']);
                    $document->setValue("ae#" . ($i + 1), date('d/m/Y',strtotime($arr[$i]['user_2_endDate'])));
                }
            }
            $document->setValue('dah', $passport_info['dah']);
            //官员信息
            $document->setValue('name_1', $idcard_info['idRzInfo']['name']);
            $document->setValue('level_1', $idcard_info['idRzInfo']['position']);
            $document->setValue('position_2', $passport_info['idRzInfo1']['position']);
            $document->setValue('level_2', $passport_info['idRzInfo1']['level']);
            $document->setValue('position_3', $passport_info['idSjInfo']['position']);
            $document->setValue('level_2', $passport_info['idRzInfo']['position']);
            //导出银行账号
            $document->setValue('payee_name', $info['payee_name']);
            $document->setValue('payee_addr', $info['payee_addr']);
            $document->setValue('aba_code', $info['aba_code']);
            $document->setValue('bank_name', $info['bank_name']);
            $document->setValue('bank_no', $info['bank_no']);
            $document->setValue('branch_bank', $info['branch_bank']);
            $document->setValue('branch_no', $info['branch_no']);

            //写入信息
            $document->setValue('first_name', $info['first_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('work_year', $info['work_year']);
            $document->setValue('work_month', $info['work_month']);
            $document->setValue('id_card', $info['id_card']);
            $document->setValue('addr', $info['addr']);
            $document->setValue('mobile', $info['mobile']);
            $document->setValue('passport_no', isset($arr[0]['user_2_number'])?$arr[0]['user_2_number']:'');
            if($info['translater_id']!=0) {
                $translater = Db::name("translator")->field('*')->where(['id'=>$info['translater_id']])->find();
                $document->setValue('fy_sex', $translater['sex']==1?'男':'女');
            } else {
                $translater = [];
                $document->setValue('fy_sex', '');
            }
            //翻译
            $document->setValue('fy_name', isset($translater['name'])?$translater['name']:'');
            $document->setValue('fy_birth_day', isset($translater['birth_day'])?$translater['birth_day']:'');
            $document->setValue('passport_idcard_no', isset($translater['passport_idcard_no'])?$translater['passport_idcard_no']:'');
            $document->setValue('fy_address', isset($translater['address'])?$translater['address']:'');


            $outdir = App::getBasePath().'../public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $info['id_card'].'.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $document->saveAs($file);
            if(!empty($cid)){
                return ['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]];
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);
        } catch (\Exception $e) {
            if(!empty($cid)){
                return ['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()];
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);

        }
    }

    //导出账号翻译
    function exportZhfy($cid='') {

        if(empty($cid)){
            $id = $this->request->request('id','','intval');
        }else{
            $id=$cid;
        }
        //$param = !empty($arr) ? $arr : $this->request->param();
        $info = Db::name("customer")->field('*')->where(['id'=>$id])->find();
        //p($info);exit;

        $idcard_info = $passport_info = [];
        $data=[];
        try {

            $dir = App::getBasePath().'../public/template/zhfy.docx';
            $document = new TemplateProcessor($dir);
            //写入信息
            $document->setValue('payee_name', $info['payee_name']);
            $document->setValue('payee_addr', $info['payee_addr']);
            $document->setValue('aba_code', $info['aba_code']);
            $document->setValue('bank_name', $info['bank_name']);
            $document->setValue('branch_bank', $info['branch_bank']);
            $document->setValue('branch_no', $info['branch_no']);

            $outdir = App::getBasePath().'../public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $info['id_card'].'账号翻译.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $document->saveAs($file);
            if(!empty($cid)){
                return ['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]];
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);
        } catch (\Exception $e) {
            if(!empty($cid)){
                return ['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()];
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);

        }
    }

    //批量导出账号翻译
    public function batchExportZhfy(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $ret=$this->exportZhfy($value);
                Log::wirte(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($ret['status']=='00' && !empty($ret['data']['file_nm'])){
                    $file=$ret['data']['file_nm'];
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 1);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>'1','msg'=>$e->getMessage()]);
        }
    }

    //导出切结书
    function exportQjs($cid='') {

        if(empty($cid)){
            $id = $this->request->request('id','','intval');
        }else{
            $id=$cid;
        }
        $info = Db::name("customer")->field('*')->where(['id'=>$id])->find();
        //p($info);exit;
        try {
            $dir = App::getBasePath().'../public/template/qjs.docx';
            $document = new TemplateProcessor($dir);
            //写入信息
            $document->setValue('first_name', $info['first_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('work_year', $info['work_year']);
            $document->setValue('work_month', $info['work_month']);
            $document->setValue('id_card', $info['id_card']);
            $document->setValue('addr', $info['addr']);

            $outdir = App::getBasePath().'../public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $info['id_card'].'切结书.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $document->saveAs($file);
            if(!empty($cid)){
                return ['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]];
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);
        } catch (\Exception $e) {
            if(!empty($cid)){
                return ['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()];
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);

        }
    }

    //批量导出切结书
    public function batchExportQjs(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $ret=$this->exportQjs($value);
                Log::wirte(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($ret['status']=='00' && !empty($ret['data']['file_nm'])){
                    $file=$ret['data']['file_nm'];
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 1);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>'1','msg'=>$e->getMessage()]);
        }
    }

    //导出授权书
    function exportSqs($cid='') {
        if(empty($cid)){
            $id = $this->request->request('id','','intval');
        }else{
            $id=$cid;
        }
        $info = Db::name("customer")->field('*')->where(['id'=>$id])->find();
        //p($info);exit;
        try {
            $dir = App::getBasePath().'../public/template/sqs.docx';
            $document = new TemplateProcessor($dir);
            //写入信息
            $document->setValue('first_name', $info['first_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('birth_day', $info['birth_day']);
            //$document->setValue('sex', $info['sex']);
            $document->setValue('id_card', $info['id_card']);
            $document->setValue('addr', $info['addr']);

            $outdir = App::getBasePath().'../public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $info['id_card'].'授权书.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $document->saveAs($file);
            if(!empty($cid)){
                return ['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]];
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);
        } catch (\Exception $e) {
            if(!empty($cid)){
                return ['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()];
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);

        }
    }

    //批量导出授权书
    public function batchExportSqs(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $ret=$this->exportSqs($value);
                Log::wirte(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($ret['status']=='00' && !empty($ret['data']['file_nm'])){
                    $file=$ret['data']['file_nm'];
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 1);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>'1','msg'=>$e->getMessage()]);
        }
    }

    //导出文件证明申请表
    function exportWjzmsqb($cid='') {
        if(empty($cid)){
            $id = $this->request->request('id','','intval');
        }else{
            $id=$cid;
        }
        $info = Db::name("customer")->field('*')->where(['id'=>$id])->find();
        //p($info);exit;
        try {
            $dir = App::getBasePath().'../public/template/wjzmsqb.docx';
            $document = new TemplateProcessor($dir);
            //写入信息
            $document->setValue('first_name', $info['first_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('last_name', $info['last_name']);
            $document->setValue('birth_day', $info['birth_day']);
            $document->setValue('mobile', $info['mobile']);
            $document->setValue('id_card', $info['id_card']);
            $document->setValue('addr', $info['addr']);

            $outdir = App::getBasePath().'../public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $info['id_card'].'文件证明申请表.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $document->saveAs($file);
            if(!empty($cid)){
                return ['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]];
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);
        } catch (\Exception $e) {
            if(!empty($cid)){
                return ['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()];
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);

        }
    }

    //批量导出文件证明申请表
    public function batchExportWjsqb(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $ret=$this->exportWjzmsqb($value);
                Log::wirte(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($ret['status']=='00' && !empty($ret['data']['file_nm'])){
                    $file=$ret['data']['file_nm'];
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 1);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>'1','msg'=>$e->getMessage()]);
        }
    }
    //批量导出身份证护照
    public function batchExport(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $ret=$this->exportWord($value);
                Log::wirte(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($ret['status']=='00' && !empty($ret['data']['file_nm'])){
                    $file=$ret['data']['file_nm'];
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 1);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>'1','msg'=>$e->getMessage()]);
        }
    }


}

